package com.lk.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;

import java.nio.charset.StandardCharsets;

public class ProxyToServerHandler extends ChannelInboundHandlerAdapter {

    private final Channel inboundChannel;


    public ProxyToServerHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        System.out.println("ProxyToServerHandler: channelActive");
        ctx.read();

//            String msg = "hello Server!";
//            ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
//            encoded.writeBytes(msg.getBytes());
//            ctx.write(encoded);
//            ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("client :channelRead"); // 接收服务器的消息并打印
        inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("aaaaa");
        cause.printStackTrace();
        ctx.close(); // 发生异常时关闭连接
    }
}
